package com.example.imtoken.view.exit

import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.example.imtoken.R
import com.example.imtoken.core.OnBottomSheetDialogFragmentListener
import com.example.imtoken.databinding.ExitFragmentBinding
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

class ExitFragment : BottomSheetDialogFragment() {

    private val viewModel: ExitViewModel by lazy {
        ViewModelProvider(this).get(ExitViewModel::class.java)
    }

    private lateinit var dataBinding: ExitFragmentBinding

    private var listener: OnBottomSheetDialogFragmentListener? = null

    private var mBehavior: BottomSheetBehavior<View>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //重写样式,设置dialog背景色为透明
        setStyle(STYLE_NORMAL, R.style.AppBottomSheet)
    }

    @SuppressLint("ResourceType")
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
        dataBinding =
            DataBindingUtil.inflate(
                layoutInflater,
                R.layout.exit_fragment,
                null,
                false
            )
        dialog.setContentView(dataBinding.root)
        mBehavior = BottomSheetBehavior.from(dataBinding.root.parent as View)
        mBehavior?.addBottomSheetCallback(mBottomSheetBehaviorCallback)
        initViewContent()
        return dialog
    }

    private fun initViewContent() {
        initClick()
    }

    private fun initClick() {
        dataBinding.tvExit.setOnClickListener {
            listener?.dialog(this)
        }
        dataBinding.ivBack.setOnClickListener { this.dismiss() }
    }

    override fun onStart() {
        super.onStart()
        mBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
    }

    private val mBottomSheetBehaviorCallback = object : BottomSheetBehavior.BottomSheetCallback() {
        override fun onStateChanged(bottomSheet: View, newState: Int) {
            if (newState == BottomSheetBehavior.STATE_DRAGGING)
                mBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
        }

        override fun onSlide(bottomSheet: View, slideOffset: Float) {

        }

    }

    fun setOnBottomSheetDialogFragmentListener(onBottomSheetDialogFragmentListener: OnBottomSheetDialogFragmentListener) {
        this.listener = onBottomSheetDialogFragmentListener
    }

}